/**
 * Copyright (C) 2017 - 2020 https://github.com/joewee
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.bifrost.listener;

import com.bifrost.constant.SendCouponType;
import com.bifrost.entity.Customer;
import com.bifrost.exception.BonusPointsNotEnoughException;
import com.bifrost.game.entity.LotteryAward;
import com.bifrost.game.entity.LotteryGameWinner;
import com.bifrost.game.event.LotteryGameWinEvent;
import com.bifrost.service.CouponService;
import com.bifrost.service.CustomerService;
import com.bifrost.wechat.entity.WechatAccount;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 *
 *
 *@author joewee
 *@version 1.0.0
 *@Date 2018/5/14 17:40
 */
@Component
@Async
public class LotteryGameWinListener implements ApplicationListener<LotteryGameWinEvent> {
   private static final Logger LOGGER = LoggerFactory.getLogger(LotteryGameWinListener.class);
    String templateId;
    @Autowired
    CouponService couponService;
    @Autowired
    CustomerService customerService;
    @Override
    public void onApplicationEvent(LotteryGameWinEvent lotteryGameWinEvent) {
        LotteryGameWinner winner =(LotteryGameWinner) lotteryGameWinEvent.getSource();
       if(winner!=null){
           if (LOGGER.isDebugEnabled()) {
               LOGGER.debug("{}参与活动{}获得奖品{}",winner.getWinnerId(),winner.getLotteryGame().getName(),winner.getLotteryAward().getName());
           }
          LotteryAward lotteryAward = winner.getLotteryAward();
           String openId =winner.getWinnerId();
          Customer customer = customerService.findByOpenId(openId);
           if(lotteryAward!=null&&customer!=null){
               Long couponId = lotteryAward.getCouponId();
               LotteryAward.AwardType type = lotteryAward.getAwardType();
               if(LotteryAward.AwardType.COUPON.equals(type)){
                   try {
                       couponService.getCoupon(customer,couponId, SendCouponType.LOTTERY);
                   } catch (BonusPointsNotEnoughException e) {
                       LOGGER.error(e.getErrorMsg(),e);
                   }
               }
           }
           /*WxMpTemplateData subTitle = new WxMpTemplateData("first", "尊敬的顾客您好，您已成功支付订单,我们将会为您尽快发货", "#173177");
           WxMpTemplateData orderNumber = new WxMpTemplateData("keyword1", order.getOrderNumber(), "#173177");
           WxMpTemplateData total = new WxMpTemplateData("keyword2", String.format("%.2f", order.getOrderTotal()), "#173177");
           //WxMpTemplateData time =new WxMpTemplateData("remark",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(order.getUpdatedTimestamp()),"#173177");
           WxMpTemplateData remark = new WxMpTemplateData("remark", "欢迎下次光临", "#173177");
           List<WxMpTemplateData> dataList = new ArrayList<>();
           dataList.add(subTitle);
           dataList.add(orderNumber);
           dataList.add(total);
           dataList.add(remark);
           WxMpTemplateMessage message = WxMpTemplateMessage.builder()
                   .templateId(templateId).toUser(openId).url(String.format("%s?orderId=%d", viewOrderUrl, order.getOrderId()))
                   .data(dataList).build();
           try {
               Long storeId = order.getMerchantStore().getMerchantId();
               WechatAccount account = wechatAccountService.getAccount(storeId);
               if(account!=null){
                   WxMpService service = wxServiceContext.getWxService(account.getAppId());
                   service.getTemplateMsgService().sendTemplateMsg(message);
               }
           } catch (WxErrorException e) {
               LOGGER.error(e.getMessage(), e);
           }*/
       }
    }
}
